<?php

/**
 * Address actions.
 *
 * @package    ProdAssistant
 * @subpackage Address
 * @author     Paweł Świtalla
 * @version    SVN: $Id: actions.class.php 23810 2009-11-12 11:07:44Z Kris.Wallsmith $
 */
class AddressActions extends sfActions
{
  private $core;
  private $url;
  
  public function preExecute()
  {
    $this->core = PACore::getInstance();
    $this->url = $this->core->generateAppUrl('Production', 'addressesList');
  }
  public function executeCreate(sfWebRequest $request)
  {
    $url = $request->getReferer();
    $this->form = new AddressForm();
    if($request->isMethod('post'))
    {
      $this->form->bind($request->getParameter('address'));
      if($this->form->isValid())
      {
        $address = $this->form->save();
        if($request->isXmlHttpRequest())
        {
          $this->getResponse()->setContent('location@'.$url."#");
          return sfView::NONE;
        }
        else $this->redirectIf($address, $url);;
      }
    }
    if($request->isXmlHttpRequest())
    {
      $errors = '';
      foreach($this->form->getFormFieldSchema() as $field){
        if($field->hasError()){
          $errors .= ucfirst($field->getName()).': '.$field->getError()."\n";
        }
      }
      $this->getResponse()->setContent('error@'.$errors."#");
      return sfView::NONE;
    }
    else $this->referer = $url;
  }
  
  public function executeDelete(sfWebRequest $request)
  {
    $url = $request->getReferer();
    $address = Doctrine_Core::getTable('Address')->find($request->getParameter('id'));
    if($address instanceof Address)
    {
      $address->delete();
      $this->redirect($url);
    }
  }

  public function executeUpdate(sfWebRequest $request)
  {
    $url = $request->getReferer();
    $address = Doctrine_Core::getTable('Address')->find($request->getParameter('id'));
    $this->form = new AddressForm($address);
    if($request->isMethod('put'))
    {
      $this->form->bind($request->getParameter('address'));
      if($this->form->isValid())
      {
        $address = $this->form->save();
        if($request->isXmlHttpRequest())
        {
          $this->getResponse()->setContent('location@'.$url."#");
          return sfView::NONE;
        }
        else $this->redirectIf($address, $url);;
      }
    }
    if($request->isXmlHttpRequest())
    {
      $errors = '';
      foreach($this->form->getFormFieldSchema() as $field){
        if($field->hasError()){
          $errors .= ucfirst($field->getName()).': '.$field->getError()."\n";
        }
      }
      $this->getResponse()->setContent('error@'.$errors."#");
      return sfView::NONE;
    }
    else $this->referer = $url;
  }
  
  public function executeShow(sfWebRequest $request)
  {
  
  }
  
  public function executeAddressesList(sfWebRequest $request)
  {
    $this->addresses = Doctrine_Core::getTable('Address')->findAll();
    $this->setLayout(PACore::getLayoutsDir().'/clear');
  }
}
